package guicommon;

import java.nio.CharBuffer;

public abstract class Message {

    public static final int MAX_MESSAGE_CAPACITY = 1024;

    protected Header header;

    protected Body body;

    protected Message(Header header, CharBuffer buffer) {
        this.header = header;
        this.body = new Body();
        ParseBody(buffer);
    }

    protected Message(Header header) {
        this.header = header;
        this.body = new Body();
    }

    public static Message ParseMessage(CharBuffer charBuffer) throws Exception {
        char[] headerBuffer = new char[Header.HEADER_LENGTH];
        charBuffer.get(headerBuffer, 0, Header.HEADER_LENGTH);
        Header header = new Header(headerBuffer);
        return MessageFactory.GetInstance().CreateMessage(header, charBuffer);
    }

    protected abstract void ParseBody(CharBuffer charBuffer);

    public CharSequence GetCharSequence() {
        try {
        CharBuffer result = CharBuffer.allocate(Header.HEADER_LENGTH + header.GetBodyLength());
        header.ToCharSequence(result);
        body.ToCharSequence(result);
        result.position(0);
        return result;
        }
        catch (Exception e) {
            CharBuffer result = CharBuffer.allocate(Header.HEADER_LENGTH + header.GetBodyLength());
            header.ToCharSequence(result);
            body.ToCharSequence(result);
            result.position(0);
            return result;
        }
    }

    public void AddParseBodyField(String key, String value) {
        body.AddField(key, value);
    }
    
    public void SetBodyField(String key, String value) {
        body.AddField(key, value);
        header.IncrementLength(key.length() + value.length() + 2);
    }

    public String GetBodyField(String key) {
        return body.GetField(key);
    }

    public MessageType GetMessageType() {
        return header.GetMessageType();
    }

    public int GetMessageCode() {
        return header.GetMessageCode();
    }
}
